package com.hskn.hss.module.user.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.constant.CommonConstant;
import com.hskn.hss.core.page.TableDataInfo;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.entity.TreeEntity;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.alarmcar.entity.AlarmCar;
import com.hskn.hss.module.alarmcar.mapper.AlarmCarMapper;
import com.hskn.hss.module.alarmperson.entity.AlarmPerson;
import com.hskn.hss.module.alarmperson.mapper.AlarmPersonMapper;
import com.hskn.hss.module.alarmsheshi.entity.AlarmSheshi;
import com.hskn.hss.module.alarmsheshi.mapper.AlarmSheshiMapper;
import com.hskn.hss.module.bigscreen.service.IBigScreenService;
import com.hskn.hss.module.carviolation.entity.CarViolation;
import com.hskn.hss.module.carviolation.mapper.CarViolationMapper;
import com.hskn.hss.module.dataBigscreen.vo.AbnormalTypeVo;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.mapper.SysDepartMapper;
import com.hskn.hss.module.dlbjviolation.entity.DlbjViolation;
import com.hskn.hss.module.dlbjviolation.mapper.DlbjViolationMapper;
import com.hskn.hss.module.eventtoremind.entity.EventToRemind;
import com.hskn.hss.module.eventtoremind.mapper.EventToRemindMapper;
import com.hskn.hss.module.menu.entity.SysMenu;
import com.hskn.hss.module.menu.service.ISysMenuService;
import com.hskn.hss.module.messageFlowRecords.domain.MessageFlowRecords;
import com.hskn.hss.module.messageFlowRecords.service.IMessageFlowRecordsService;
import com.hskn.hss.module.role.entity.SysRole;
import com.hskn.hss.module.role.mapper.SysRoleMapper;
import com.hskn.hss.module.sysinfo.entity.SysInfo;
import com.hskn.hss.module.sysinfo.mapper.SysInfoMapper;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.mapper.TlCarMapper;
import com.hskn.hss.module.tlemployee.entity.TlEmployee;
import com.hskn.hss.module.tlemployee.mapper.TlEmployeeMapper;
import com.hskn.hss.module.tlfacilities.entity.TlFacilities;
import com.hskn.hss.module.tlfacilities.mapper.TlFacilitiesMapper;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.entity.UserFull;
import com.hskn.hss.module.user.mapper.UserMapper;
import com.hskn.hss.module.user.service.IUserService;
import com.hskn.hss.module.userdepart.entity.SysUserDepart;
import com.hskn.hss.module.userdepart.service.ISysUserDepartService;
import com.hskn.hss.module.userrole.entity.SysUserRole;
import com.hskn.hss.module.userrole.mapper.SysUserRoleMapper;
import com.hskn.hss.module.userrole.service.ISysUserRoleService;
import com.hskn.hss.utils.*;
import com.hskn.hss.utils.redis.RedisUtil;
import com.hskn.hss.utils.redis.key.LoginUidAndTicketKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2020-11-16
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    UserMapper userMapper;

    @Autowired
    ISysUserRoleService sysUserRoleService;

    @Resource
    SysUserRoleMapper sysUserRoleMapper;

    @Resource
    SysRoleMapper sysRoleMapper;

    @Autowired
    ISysUserDepartService sysUserDepartService;

    @Autowired
    ISysMenuService sysMenuService;

    @Resource
    SysDepartMapper sysDepartMapper;

    @Resource
    EventToRemindMapper eventToRemindMapper;

    @Resource
    private SysInfoMapper sysInfoMapper;

    @Resource
    private TlCarMapper tlCarMapper;

    @Resource
    private AlarmCarMapper alarmCarMapper;

    @Resource
    private CarViolationMapper carViolationMapper;

    @Resource
    private TlFacilitiesMapper tlFacilitiesMapper;

    @Resource
    private AlarmSheshiMapper alarmSheshiMapper;

    @Resource
    private TlEmployeeMapper tlEmployeeMapper;

    @Resource
    private AlarmPersonMapper alarmPersonMapper;

    @Resource
    private DlbjViolationMapper dlbjViolationMapper;

    @Autowired
    private IBigScreenService bigScreenService;

    @Autowired
    private IMessageFlowRecordsService messageFlowRecordsService;

    @Override
    public JSONObject loginByPwd(JSONObject params) throws HssException {
        log.info("===开始登录");
        String account = params.getString("account");
        String password = params.getString("password");
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
            throw new HssException("账号或密码错误！");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getAccount, account);
        User user = userMapper.selectOne(queryWrapper);
        if (StringUtils.isEmpty(user)) {
            throw new HssException("账号或密码错误！");
        }
        String newMD5 = Tools.encryptPassword(password, user.getSalt());
        if (!user.getPassword().equals(newMD5)) {
            throw new HssException("账号或密码错误！");
        }
        List<SysRole> sysRoleList = getSysRoleByUId(user.getUid());
        checkJurisdiction(params.getInteger("loginType"), sysRoleList);
        user.setTimestamp(System.currentTimeMillis());
        String userStr = JSONObject.toJSONString(user);
        String ticket = Tools.createTicket(userStr);
        if (StringUtils.isEmpty(ticket)) {
            throw new HssException("数据加密异常！");
        }
        Jedis jedis = null;
        try {
            //保存或更新redis中的ticket有效期
            jedis = JedisPoolUtils.getJedis();
            log.info("===登录-获取redis信息，jedis={},ticket={}", jedis, ticket);
            SysInfo sysInfo = sysInfoMapper.selectById(1);
            String existJedis = jedis.get(ticket);
            if (StringUtils.isEmpty(existJedis)) {
                jedis.set(ticket, ticket, "NX", "EX", 24 * 60 * 60 * sysInfo.getTimeoutDay());
            } else {
                jedis.set(ticket, ticket, "XX", "EX", 24 * 60 * 60 * sysInfo.getTimeoutDay());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("==登录报错", e);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }

        JSONObject userJson = JSON.parseObject(userStr);
        userJson.put("ticket", ticket);
        userJson.put("uid", user.getUid());
        userJson.remove("password");
        userJson.remove("salt");
        //保存用户ID和ticket到redis
        RedisUtil.setList(LoginUidAndTicketKey.token, user.getUid(), ticket);
        return userJson;
    }

    private void checkJurisdiction(Integer loginType, List<SysRole> sysRoleList) throws HssException {
        Boolean isManagementEnd = false;
        Boolean isClient = false;
        Boolean isPC = false;
        for (SysRole sysRole : sysRoleList) {
            Integer roleType = sysRole.getRoleType();
            Integer platform = sysRole.getPlatform();
            if (!isManagementEnd) {
                if ((roleType == 1 && platform == 2) || (roleType == 1 && platform == 0)) {
                    isManagementEnd = true;
                }
            }
            if (!isClient) {
                if ((roleType == 2 && platform == 2) || (roleType == 2 && platform == 0)) {
                    isClient = true;
                }
            }
            if (!isPC) {
                if (platform == 1 || platform == 0) {
                    isPC = true;
                }
            }
            if (sysRole.getId().equals("00000000")) {
                isManagementEnd = true;
                isClient = true;
                isPC = true;
                break;
            }
        }
        String msg = "";

        if (Objects.nonNull(loginType)) {
            if (loginType == 1 && !isManagementEnd) {
                msg = "此账号不能登录管理端";
            }
            if (loginType == 2 && !isClient) {
                msg = "此账号不能登录用户端";
            }
            if (!(loginType == 1 && isManagementEnd) && Objects.nonNull(loginType) && !(loginType == 2 && isClient)) {
                throw new HssException(msg);
            }
        } else {
            if (!isPC) {
                throw new HssException("此账号不能登录web端");
            }
        }


    }

    @Override
    public void modifyPwd(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String pwdOld = params.getString("pwdOld");
        String pwdNew = params.getString("pwdNew");
        if (StringUtils.isEmpty(pwdOld) || StringUtils.isEmpty(pwdNew)) {
            throw new HssException("参数错误！");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUid, uid);
        User user = userMapper.selectOne(queryWrapper);
        if (StringUtils.isEmpty(user)) {
            throw new HssException("账号或密码错误！");
        }
        if (!user.getPassword().equals(Tools.encryptPassword(pwdOld, user.getSalt()))) {
            throw new HssException("账号或密码错误！");
        }
        user.setPassword(Tools.encryptPassword(pwdNew, user.getSalt()));
        userMapper.updateById(user);
    }

    @Override
    @Transactional
    public void addUser(JSONObject params) throws HssException {
        // TODO: 2021/4/29 判断当前用户 uid 有没有添加用户的权限
        if (false) {
            throw new HssException("无权操作");
        }
        if (!params.containsKey("account") || !params.containsKey("password")) {
            throw new HssException("参数错误");
        }
        User user = JSON.parseObject(params.toJSONString(), User.class);
        String salt = StringUtils.getRandomString(8);
        user.setSalt(salt);
        if (params.containsKey("roleids") && StringUtils.isNotEmpty(params.getString("roleids"))) {
            AtomicReference<Integer> isAdmin = new AtomicReference<Integer>(2);
            String[] roleIds = params.getString("roleids").split(",");
            List<SysRole> roleList = sysRoleMapper.selectList(new QueryWrapper<SysRole>().lambda().in(SysRole::getId, roleIds));
            roleList.forEach(r -> {
                if (r.getId().equals("00000000")) {
                    isAdmin.set(1);
                }
            });
            user.setIsAdmin(isAdmin.get());
        }
        user.setPassword(Tools.encryptPassword(user.getPassword(), salt));
        userMapper.insert(user);
        // 绑定角色
        String roleidsStr = params.getString("roleids");
        if (StringUtils.isNotEmpty(roleidsStr)) {
            List<SysUserRole> sysUserRoleList = new ArrayList<>();
            String[] roleids = roleidsStr.split(",");
            for (String roleid : roleids) {
                SysUserRole sysUserRole = new SysUserRole(StringUtils.uuid(), user.getUid(), roleid);
                sysUserRoleList.add(sysUserRole);
            }
            sysUserRoleService.saveBatch(sysUserRoleList);
        }
        // 绑定部门
        String departId = params.getString("depid");
        if (StringUtils.isNotEmpty(departId)) {
            JSONObject data = new JSONObject();
            JSONObject sysUserDepart = new JSONObject();
            sysUserDepart.put("userid", user.getUid());
            sysUserDepart.put("depid", departId);
            data.put("data", sysUserDepart);
            sysUserDepartService.insert(data);
        }
        // 提醒设置
        EventToRemind eventToRemind = new EventToRemind();
        eventToRemind.setCreateUid(user.getUid());
        eventToRemind.setCreateTime(LocalDateTime.now());
        eventToRemindMapper.insert(eventToRemind);
    }

    @Override
    public JSONObject mList(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        Long page = (StringUtils.isEmpty(params.getLong("page")) || params.getLong("page") == 0) ? 1 : params.getLong("page");
        Long size = (StringUtils.isEmpty(params.getLong("size")) || params.getLong("size") == 0) ? 10 : params.getLong("size");
        params.put("offset", (page - 1) * size);
        params.put("limit", size);
        String roleids = params.getString("roleids");
        if (StringUtils.isNotEmpty(roleids)) {
            String[] roleidArr = roleids.split(",");
            if (roleidArr.length > 0) {
                params.put("roleids", Arrays.asList(roleidArr));
            }
        }
        JSONObject res = new JSONObject();
        List<UserFull> userFulls = userMapper.getUserList(params);
        Long userCount = userMapper.getUserListCount(params);
        res.put("users", userFulls);
        res.put("total", userCount);
        res.put("current", page);
        res.put("pages", (int) Math.ceil(userCount / size));
        res.put("size", userFulls.size());
        return res;
    }

    @Override
    @Transactional
    public void mUpdate(JSONObject params) throws HssException {
        // TODO: 2021/5/4 权限 uid 校验
        User user = JSON.parseObject(params.toJSONString(), User.class);
        if (StringUtils.isNotEmpty(user.getPassword())) {
            String salt = StringUtils.getRandomString(8);
            user.setSalt(salt);
            user.setPassword(Tools.encryptPassword(user.getPassword(), salt));
        }
        if (params.containsKey("roleids") && StringUtils.isNotEmpty(params.getString("roleids"))) {
            AtomicReference<Integer> isAdmin = new AtomicReference<Integer>(2);
            String[] roleIds = params.getString("roleids").split(",");
            List<SysRole> roleList = sysRoleMapper.selectList(new QueryWrapper<SysRole>().lambda().in(SysRole::getId, roleIds));
            roleList.forEach(r -> {
                if (r.getId().equals("00000000")) {
                    isAdmin.set(1);
                }
            });
            user.setIsAdmin(isAdmin.get());
        }
        userMapper.updateById(user);
        // 机构负责人联系方式关联修改
        if (StringUtils.isNotEmpty(user.getUid())) {
            UpdateWrapper<SysDepart> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(SysDepart::getPrincipalUid, user.getUid()).set(SysDepart::getMobile, user.getPhone());
            sysDepartMapper.update(null, updateWrapper);
        }
        // 换绑角色
        String roleidsStr = params.getString("roleids");
        if (StringUtils.isNotEmpty(roleidsStr)) {
            String[] roleids = roleidsStr.split(",");
            sysUserRoleService.updateByUserid(user.getUid(), roleids);
        }
        // 换绑部门
        String departId = params.getString("depid");
        if (StringUtils.isNotEmpty(departId)) {
            sysUserDepartService.updateByUserid(user.getUid(), departId);
        }
    }

    @Override
    @Transactional
    public void listUpdate(User user) throws HssException {
        // TODO: 2021/5/4 权限 uid 校验
        String ids = user.getUids();
        String[] idArray = ids.split(",");

        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.lambda().in(User::getUid, idArray);
        if (StringUtils.isNotEmpty(user.getPassword())) {
            String salt = StringUtils.getRandomString(8);
            user.setSalt(salt);
            user.setPassword(Tools.encryptPassword(user.getPassword(), salt));
        }
        userMapper.update(user, userUpdateWrapper);
        // 换绑角色
        String roleidsStr = user.getRoleids();
        if (StringUtils.isNotEmpty(roleidsStr)) {
            String[] roleids = roleidsStr.split(",");
            sysUserRoleService.updateByUserid(user.getUid(), roleids);
        }
        // 换绑部门
        String departId = user.getDepid();
        if (StringUtils.isNotEmpty(departId)) {
            sysUserDepartService.updateByUserid(user.getUid(), departId);
        }
    }

    @Override
    @Transactional
    public void mDel(JSONObject params) throws HssException {
        // TODO: 2021/5/4 权限 uid 校验
        String mUid = params.getString("uid");
        if (StringUtils.isEmpty(mUid)) {
            throw new HssException("参数错误");
        }
        userMapper.deleteById(mUid);
        sysUserRoleService.deleteByUid(mUid);
        sysUserDepartService.deleteByUid(mUid);
    }

    @Override
    @Transactional
    public AjaxResult deletebatchbyid(User user) throws HssException {
        // TODO: 2021/5/4 权限 uid 校验
        String mUids = user.getUids();
        String[] idArray = mUids.split(",");
        if (StringUtils.isEmpty(idArray)) {
            throw new HssException("参数错误");
        }
        userMapper.deleteBatchIds(Arrays.asList(idArray));
        QueryWrapper<SysUserRole> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.lambda().in(SysUserRole::getUserid, idArray);
        QueryWrapper<SysUserDepart> departQueryWrapper = new QueryWrapper<>();
        departQueryWrapper.lambda().in(SysUserDepart::getUserid, idArray);
        sysUserRoleService.remove(roleQueryWrapper);
        sysUserDepartService.remove(departQueryWrapper);
        return AjaxResult.success("操作成功");
    }

    @Override
    public UserFull detail() throws HssException {
        String uid = LoginUtils.getUser().getUid();
        UserFull userFull = userMapper.getUserDetail(uid);
        List<SysMenu> menus = new ArrayList<>();
        Map<String, SysMenu> sysMenuMap = new HashMap<>();
        if (userFull.getIsAdmin() != 1) {
            menus = sysMenuService.getMenuListByUserid(uid);
            sysMenuMap = sysMenuService.getSysMenuMap(new QueryWrapper<SysMenu>().lambda().eq(SysMenu::getStatus, "0"));
        } else {
            menus = sysMenuService.selectList(new QueryWrapper<SysMenu>().lambda().eq(SysMenu::getStatus, "0"));
        }
        if (MapUtils.isNotEmpty(sysMenuMap)) {
            List<SysMenu> sysMenuList = new ArrayList<>();
            for (SysMenu menu : menus) {
                sysMenuList.add(menu);
                sysMenuList.addAll(MenuTreeUtil.getAllChildList(menu, sysMenuMap));
            }
            if (CollectionUtils.isNotEmpty(sysMenuList)) {
                userFull.setMenus(sysMenuList.stream().distinct().collect(Collectors.toList()));
            } else {
                userFull.setMenus(new ArrayList<>());
            }
        } else {
            if (CollectionUtils.isNotEmpty(menus)) {
                userFull.setMenus(menus.stream().distinct().collect(Collectors.toList()));
            } else {
                userFull.setMenus(new ArrayList<>());
            }
        }
        User user = JSONObject.parseObject(JSON.toJSONString(userFull), User.class);
        List<SysRole> sysRoleList = LoginUtils.getLoginRoleList(user);
        if (user.getIsAdmin() != 1) {
            userFull.setPermissions(LoginUtils.getPermissions(sysRoleList));
        } else {
            userFull.setPermissions("***");
        }
        return userFull;
    }

    @Override
    public User getUserDetail(String uid) {
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUid, uid));
        return user;
    }

    @Override
    public List<SysRole> getSysRoleByUId(String uid) {
        List<SysUserRole> userRoleList = sysUserRoleMapper.selectList(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserid, uid));
        if (CollectionUtils.isNotEmpty(userRoleList)) {
            List<String> ids = userRoleList.stream().map(SysUserRole::getRoleid).collect(Collectors.toList());
            return sysRoleMapper.selectList(new QueryWrapper<SysRole>().lambda().in(SysRole::getId, ids));
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public void processingIsAdminUser() {
        List<User> userList = list();
        for (User user : userList) {
            List<SysRole> sysRoleList = getSysRoleByUId(user.getUid());
            AtomicReference<Integer> isAdmin = new AtomicReference<Integer>(2);
            sysRoleList.forEach(r -> {
                if (r.getId().equals("00000000")) {
                    isAdmin.set(1);
                }
            });
            user.setIsAdmin(isAdmin.get());
        }
        updateBatchById(userList);
    }

    @Override
    public List<TreeEntity> userTree() throws HssException {
        List<TreeEntity> treeList = sysDepartMapper.getTreeList();
        List<TreeEntity> userTree = userMapper.getUserTree();
        treeList.addAll(userTree);
        List<TreeEntity> trees = TreeUtil.RecursiveAddress(treeList);
        return trees;
    }

    @Override
    public Map<String, User> getUserMap() {
        List<User> userList = userMapper.selectList(new QueryWrapper<>());
        Map<String, User> userMap = new HashMap<>();
        if (!userList.isEmpty()) {
            userMap = GroupingByUtils.getGroupingForMapEntity(userList, User::getUid, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }
        return userMap;
    }


    @Override
    public TableDataInfo abnormalByUserId(JSONObject params) {

        String uid = LoginUtils.getUser().getUid();
        if (StringUtils.isEmpty(uid)) {
            return null;
        }
        User user = userMapper.selectById(uid);
        if (Objects.isNull(user)) {
            return null;
        }

        Map<String, Map<String, MessageFlowRecords>> messageFlowRecordsByUserIdAndMessageIdMap = messageFlowRecordsService.getMessageFlowRecordsByUserIdAndMessageIdMap();
        Map<String, MessageFlowRecords> messageFlowRecordsByMessageIdMap = new HashMap<>();
        if (Objects.nonNull(messageFlowRecordsByUserIdAndMessageIdMap)) {
            messageFlowRecordsByMessageIdMap = messageFlowRecordsByUserIdAndMessageIdMap.get(uid);
        }

        List<Map> dataBigScreenAbnormalResultList = new ArrayList<>();
        String startTime = params.getString("startTime");
        String endTime = params.getString("endTime");
        String alarmTypeName = params.getString("alarmTypeName");

        TlCar tlCar = null;
        TlFacilities tlFacilities = null;
        TlEmployee tlEmployee = null;

        Integer roleType = LoginUtils.getLoginUserIdentity();

        if (CommonConstant.ROLE_USER == roleType) {
            //查询绑定的车辆
            QueryWrapper<TlCar> tlCarQueryWrapper = new QueryWrapper<>();
            tlCarQueryWrapper.lambda().eq(TlCar::getBindaccount, uid);
            tlCarQueryWrapper.lambda().last(" LIMIT 1");
            tlCar = tlCarMapper.selectOne(tlCarQueryWrapper);

            //查询负责的设施
            QueryWrapper<TlFacilities> tlFacilitiesQueryWrapper = new QueryWrapper<>();
            tlFacilitiesQueryWrapper.lambda().eq(TlFacilities::getPrincipal, uid);
            tlFacilitiesQueryWrapper.lambda().last(" LIMIT 1");
            tlFacilities = tlFacilitiesMapper.selectOne(tlFacilitiesQueryWrapper);

            //查询绑定的人员档案
            QueryWrapper<TlEmployee> tlEmployeeQueryWrapper = new QueryWrapper<>();
            tlEmployeeQueryWrapper.lambda().eq(TlEmployee::getBindaccount, uid);
            tlEmployeeQueryWrapper.lambda().last(" LIMIT 1");
            tlEmployee = tlEmployeeMapper.selectOne(tlEmployeeQueryWrapper);
        }

        //当日车辆报警
        QueryWrapper<AlarmCar> alarmCarQueryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(tlCar)) {
            alarmCarQueryWrapper.lambda().eq(AlarmCar::getCarId, tlCar.getId());
        } else if (CommonConstant.ROLE_USER == roleType) {
            alarmCarQueryWrapper.lambda().eq(AlarmCar::getCarId, null);
        }
        if (StringUtils.isNotEmpty(startTime)) {
            alarmCarQueryWrapper.lambda().ge(AlarmCar::getAlarmTime, startTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            alarmCarQueryWrapper.lambda().le(AlarmCar::getAlarmTime, endTime);
        }
        if (StringUtils.isNotEmpty(alarmTypeName)) {
            alarmCarQueryWrapper.lambda().le(AlarmCar::getAlarmTypeName, alarmTypeName);
        }
        List<AlarmCar> alarmCarList = alarmCarMapper.selectList(alarmCarQueryWrapper);
        for (AlarmCar alarmCar : alarmCarList
        ) {
//                AbnormalVo dataBigScreenAbnormalResult = new AbnormalVo();
//                dataBigScreenAbnormalResult.setId(alarmCar.getAlarmCarId());
//                dataBigScreenAbnormalResult.setMessage(alarmCar.getCarName() + alarmCar.getContent());
//                dataBigScreenAbnormalResult.setValue(alarmCar.getAlarmValue());
//                dataBigScreenAbnormalResult.setTime(alarmCar.getAlarmTime());
//                dataBigScreenAbnormalResult.setType(0);
            MessageFlowRecords messageFlowRecords = messageFlowRecordsByMessageIdMap.get(alarmCar.getAlarmCarId());
            if (Objects.nonNull(messageFlowRecords)) {
                alarmCar.setIsRead(1);
            } else {
                alarmCar.setIsRead(0);
            }

            Map map = JSON.parseObject(JSON.toJSONString(alarmCar), Map.class);
            map.put("type", 0);
            dataBigScreenAbnormalResultList.add(map);
        }

        //当日车辆违规
        QueryWrapper<CarViolation> carViolationQueryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(tlCar)) {
            carViolationQueryWrapper.lambda().eq(CarViolation::getCarId, tlCar.getId());
        } else if (CommonConstant.ROLE_USER == roleType) {
            carViolationQueryWrapper.lambda().eq(CarViolation::getCarId, null);
        }
        if (StringUtils.isNotEmpty(startTime)) {
            carViolationQueryWrapper.lambda().ge(CarViolation::getTime, startTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            carViolationQueryWrapper.lambda().le(CarViolation::getTime, endTime);
        }
        if (StringUtils.isNotEmpty(alarmTypeName)) {
            carViolationQueryWrapper.lambda().le(CarViolation::getRuleTypeName, alarmTypeName);
        }
        List<CarViolation> carViolationList = carViolationMapper.selectList(carViolationQueryWrapper);
        for (CarViolation carViolation : carViolationList
        ) {
//                AbnormalVo dataBigScreenAbnormalResult = new AbnormalVo();
//                dataBigScreenAbnormalResult.setId(carViolation.getCarViolationId());
//                dataBigScreenAbnormalResult.setMessage(carViolation.getCarName() + carViolation.getContent());
//                dataBigScreenAbnormalResult.setValue(carViolation.getViolationValue());
//                dataBigScreenAbnormalResult.setTime(carViolation.getTime());
//                dataBigScreenAbnormalResult.setType(1);

            MessageFlowRecords messageFlowRecords = messageFlowRecordsByMessageIdMap.get(carViolation.getCarViolationId());
            if (Objects.nonNull(messageFlowRecords)) {
                carViolation.setIsRead(1);
            } else {
                carViolation.setIsRead(0);
            }

            Map map = JSON.parseObject(JSON.toJSONString(carViolation), Map.class);
            map.put("type", 1);
            dataBigScreenAbnormalResultList.add(map);
        }


        //当日设施报警
        QueryWrapper<AlarmSheshi> alarmSheshiQueryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(tlFacilities)) {
            alarmSheshiQueryWrapper.lambda().eq(AlarmSheshi::getSheshiId, tlFacilities.getId());
        } else if (CommonConstant.ROLE_USER == roleType) {
            alarmSheshiQueryWrapper.lambda().eq(AlarmSheshi::getSheshiId, null);
        }
        if (StringUtils.isNotEmpty(startTime)) {
            alarmSheshiQueryWrapper.lambda().ge(AlarmSheshi::getAlarmTime, startTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            alarmSheshiQueryWrapper.lambda().le(AlarmSheshi::getAlarmTime, endTime);
        }
        if (StringUtils.isNotEmpty(alarmTypeName)) {
            alarmSheshiQueryWrapper.lambda().le(AlarmSheshi::getAlarmTypeName, alarmTypeName);
        }
        List<AlarmSheshi> alarmSheshiList = alarmSheshiMapper.selectList(alarmSheshiQueryWrapper);
        for (AlarmSheshi alarmSheshi : alarmSheshiList
        ) {
//                AbnormalVo dataBigScreenAbnormalResult = new AbnormalVo();
//                dataBigScreenAbnormalResult.setId(alarmSheshi.getAlarmSheshiId());
//                dataBigScreenAbnormalResult.setMessage(alarmSheshi.getSheshiName() + alarmSheshi.getContent());
//                dataBigScreenAbnormalResult.setValue(alarmSheshi.getAlarmValue());
//                dataBigScreenAbnormalResult.setTime(alarmSheshi.getAlarmTime());
//                dataBigScreenAbnormalResult.setType(0);

            MessageFlowRecords messageFlowRecords = messageFlowRecordsByMessageIdMap.get(alarmSheshi.getAlarmSheshiId());
            if (Objects.nonNull(messageFlowRecords)) {
                alarmSheshi.setIsRead(1);
            } else {
                alarmSheshi.setIsRead(0);
            }

            Map map = JSON.parseObject(JSON.toJSONString(alarmSheshi), Map.class);
            map.put("type", 0);
            dataBigScreenAbnormalResultList.add(map);
        }


        if (Objects.nonNull(tlEmployee)) {
            //当日人员报警
            QueryWrapper<AlarmPerson> alarmPersonQueryWrapper = new QueryWrapper<>();
            if (Objects.nonNull(tlEmployee)) {
                alarmPersonQueryWrapper.lambda().eq(AlarmPerson::getPersonId, tlEmployee.getId());
            } else if (CommonConstant.ROLE_USER == roleType) {
                alarmPersonQueryWrapper.lambda().eq(AlarmPerson::getPersonId, null);
            }
            if (StringUtils.isNotEmpty(startTime)) {
                alarmPersonQueryWrapper.lambda().ge(AlarmPerson::getAlarmTime, startTime);
            }
            if (StringUtils.isNotEmpty(endTime)) {
                alarmPersonQueryWrapper.lambda().le(AlarmPerson::getAlarmTime, endTime);
            }
            if (StringUtils.isNotEmpty(alarmTypeName)) {
                alarmPersonQueryWrapper.lambda().le(AlarmPerson::getAlarmTypeName, alarmTypeName);
            }
            List<AlarmPerson> alarmPersonList = alarmPersonMapper.selectList(alarmPersonQueryWrapper);
            for (AlarmPerson alarmPerson : alarmPersonList
            ) {
//                AbnormalVo dataBigScreenAbnormalResult = new AbnormalVo();
//                dataBigScreenAbnormalResult.setId(alarmPerson.getAlarmPersonId());
//                dataBigScreenAbnormalResult.setMessage(alarmPerson.getPersonName() + alarmPerson.getContent());
//                dataBigScreenAbnormalResult.setValue(new BigDecimal(String.valueOf(StringUtils.calLastedTime(alarmPerson.getAlarmStartTime(), alarmPerson.getAlarmEndTime()))));
//                dataBigScreenAbnormalResult.setTime(alarmPerson.getAlarmTime());
//                dataBigScreenAbnormalResult.setType(0);

                MessageFlowRecords messageFlowRecords = messageFlowRecordsByMessageIdMap.get(alarmPerson.getAlarmPersonId());
                if (Objects.nonNull(messageFlowRecords)) {
                    alarmPerson.setIsRead(1);
                } else {
                    alarmPerson.setIsRead(0);
                }

                Map map = JSON.parseObject(JSON.toJSONString(alarmPerson), Map.class);
                map.put("type", 0);
                dataBigScreenAbnormalResultList.add(map);
            }

            //当日人员违规
            QueryWrapper<DlbjViolation> dlbjViolationQueryWrapper = new QueryWrapper<>();
            if (Objects.nonNull(tlEmployee)) {
                dlbjViolationQueryWrapper.lambda().eq(DlbjViolation::getPersonId, tlEmployee.getId());
            } else if (CommonConstant.ROLE_USER == roleType) {
                dlbjViolationQueryWrapper.lambda().eq(DlbjViolation::getPersonId, null);
            }
            if (StringUtils.isNotEmpty(startTime)) {
                dlbjViolationQueryWrapper.lambda().ge(DlbjViolation::getDate, startTime);
            }
            if (StringUtils.isNotEmpty(endTime)) {
                dlbjViolationQueryWrapper.lambda().le(DlbjViolation::getDate, endTime);
            }
            if (StringUtils.isNotEmpty(alarmTypeName)) {
                dlbjViolationQueryWrapper.lambda().le(DlbjViolation::getViolationTypeName, alarmTypeName);
            }
            List<DlbjViolation> dlbjViolationList = dlbjViolationMapper.selectList(dlbjViolationQueryWrapper);
            for (DlbjViolation dlbjViolation : dlbjViolationList
            ) {
//                AbnormalVo dataBigScreenAbnormalResult = new AbnormalVo();
//                dataBigScreenAbnormalResult.setId(dlbjViolation.getDlbjViolationId());
//                dataBigScreenAbnormalResult.setMessage(dlbjViolation.getPersonName() + dlbjViolation.getContent());
//                dataBigScreenAbnormalResult.setValue(dlbjViolation.getViolationValue());
//                dataBigScreenAbnormalResult.setTime(dlbjViolation.getDate());
//                dataBigScreenAbnormalResult.setType(1);

                MessageFlowRecords messageFlowRecords = messageFlowRecordsByMessageIdMap.get(dlbjViolation.getDlbjViolationId());
                if (Objects.nonNull(messageFlowRecords)) {
                    dlbjViolation.setIsRead(1);
                } else {
                    dlbjViolation.setIsRead(0);
                }

                Map map = JSON.parseObject(JSON.toJSONString(dlbjViolation), Map.class);
                map.put("type", 1);
                dataBigScreenAbnormalResultList.add(map);
            }
        }

        List<Map> alarmMapList = new ArrayList<>();
        List<Map> violationMapList = new ArrayList<>();
        Integer type = Integer.valueOf(params.getString("type"));
        if (StringUtils.isNotEmpty(type)) {
            for (Map map :
                    dataBigScreenAbnormalResultList) {
                if ("0".equals(String.valueOf(map.get("type")))) {
                    map.put("createTime", DateUtil.parseDateTime(StringUtils.tsToDate(Long.valueOf(String.valueOf(map.get("createTime"))))));
                    alarmMapList.add(map);
                }
                if ("1".equals(String.valueOf(map.get("type")))) {
                    map.put("createTime", DateUtil.parseDateTime(StringUtils.tsToDate(Long.valueOf(String.valueOf(map.get("createTime"))))));
                    violationMapList.add(map);
                }
            }
            if (Objects.nonNull(alarmMapList) && alarmMapList.size() > 1) {
                //按照设备上传定位时间倒序排序
                Collections.sort(alarmMapList, (o1, o2) -> {
                    long alarmTime1 = Long.valueOf(String.valueOf(o1.get("alarmTime")));
                    long alarmTime2 = Long.valueOf(String.valueOf(o2.get("alarmTime")));
                    Date d1 = DateUtil.parseDateTime(StringUtils.tsToDate(alarmTime1));
                    Date d2 = DateUtil.parseDateTime(StringUtils.tsToDate(alarmTime2));
                    return d2.compareTo(d1);
                });
            }
            if (Objects.nonNull(violationMapList) && violationMapList.size() > 1) {
                //按照设备上传定位时间倒序排序
                Collections.sort(violationMapList, (o1, o2) -> {
                    String violationData1 = Objects.nonNull(o1.get("date")) ? String.valueOf(o1.get("date")) : "";
                    String violationData2 = Objects.nonNull(o2.get("date")) ? String.valueOf(o2.get("date")) : "";
                    String violationTime1 = Objects.nonNull(o1.get("time")) ? String.valueOf(o1.get("time")) : "";
                    String violationTime2 = Objects.nonNull(o2.get("time")) ? String.valueOf(o2.get("time")) : "";
                    long time1 = StringUtils.isNotEmpty(violationData1) ? Long.valueOf(violationData1) : Long.valueOf(violationTime1);
                    long time2 = StringUtils.isNotEmpty(violationData2) ? Long.valueOf(violationData2) : Long.valueOf(violationTime2);

                    Date d1 = DateUtil.parseDateTime(StringUtils.tsToDate(time1));
                    Date d2 = DateUtil.parseDateTime(StringUtils.tsToDate(time2));
                    return d2.compareTo(d1);
                });
            }
        }

        Integer pageNum = 1;
        Integer pageSize = 10;
        if (Objects.nonNull(params.get("pageNum")) && Objects.nonNull(params.get("pageSize"))) {
            pageNum = Integer.valueOf(String.valueOf(params.get("pageNum")));
            pageSize = Integer.valueOf(String.valueOf(params.get("pageSize")));
        }
        if (0 == type) {
            return Tools.buildTableDataInfo(pageNum, pageSize, alarmMapList);
        }
        if (1 == type) {
            return Tools.buildTableDataInfo(pageNum, pageSize, violationMapList);
        }
        return null;
    }

    @Override
    public List<AbnormalTypeVo> abnormalTypeByUserId(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        if (StringUtils.isEmpty(uid)) {
            return null;
        }
        List<AbnormalTypeVo> abnormalTypeList = new ArrayList<>();
        //查询绑定的车辆
        QueryWrapper<TlCar> tlCarQueryWrapper = new QueryWrapper<>();
        tlCarQueryWrapper.lambda().eq(TlCar::getBindaccount, uid);
        tlCarQueryWrapper.lambda().last(" LIMIT 1");
        TlCar tlCar = tlCarMapper.selectOne(tlCarQueryWrapper);
        if (Objects.nonNull(tlCar)) {
            List<AbnormalTypeVo> abnormalTypeVos = bigScreenService.expTypeCars();
            for (AbnormalTypeVo abnormalTypeVo : abnormalTypeVos
            ) {
                abnormalTypeList.add(abnormalTypeVo);
            }
        }

        //查询负责的设施
        QueryWrapper<TlFacilities> tlFacilitiesQueryWrapper = new QueryWrapper<>();
        tlFacilitiesQueryWrapper.lambda().eq(TlFacilities::getPrincipal, uid);
        tlFacilitiesQueryWrapper.lambda().last(" LIMIT 1");
        TlFacilities tlFacilities = tlFacilitiesMapper.selectOne(tlFacilitiesQueryWrapper);
        if (Objects.nonNull(tlFacilities)) {
            List<AbnormalTypeVo> abnormalTypeVos = bigScreenService.expTypeFacilities();
            for (AbnormalTypeVo abnormalTypeVo : abnormalTypeVos
            ) {
                abnormalTypeList.add(abnormalTypeVo);
            }
        }

        //查询绑定的人员档案
        QueryWrapper<TlEmployee> tlEmployeeQueryWrapper = new QueryWrapper<>();
        tlEmployeeQueryWrapper.lambda().eq(TlEmployee::getBindaccount, uid);
        tlEmployeeQueryWrapper.lambda().last(" LIMIT 1");
        TlEmployee tlEmployee = tlEmployeeMapper.selectOne(tlEmployeeQueryWrapper);
        if (Objects.nonNull(tlEmployee)) {
            List<AbnormalTypeVo> abnormalTypeVos = bigScreenService.expTypePerson();
            for (AbnormalTypeVo abnormalTypeVo : abnormalTypeVos
            ) {
                abnormalTypeList.add(abnormalTypeVo);
            }
        }

        Integer type = Integer.valueOf(params.getString("type"));
        if (StringUtils.isNotEmpty(type)) {
            Map<Integer, List<AbnormalTypeVo>> abnormalTypeVoMap = abnormalTypeList.stream().collect(Collectors.groupingBy(AbnormalTypeVo::getType));
            List<AbnormalTypeVo> abnormalTypeVos = abnormalTypeVoMap.get(type);
            return abnormalTypeVos;
        }

        return abnormalTypeList;
    }
}
